﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Windows.Forms;
using System.IO;
using ESOL.Controls;
using ESOL.Common.Entity;
using ESOL.Business.Mst;
using ESOL.Business.Sec;
using ESOL.Common;
using System.Reflection;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using System.Drawing;

namespace ESOL.WinUI.UICommon
{
    public class UICommonFunctions
    {
        public static void BindTreeViewByEnum(DevTreeList tree, Type enumType)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ValueMember", typeof(string));
            dt.Columns.Add("DisplayMember", typeof(string));

            Array array = Enum.GetValues(enumType);
            foreach (Enum enumValue in array)
            {
                DataRow dr = dt.NewRow();
                dr["DisplayMember"] = enumValue.ToString();
                dr["ValueMember"] = Convert.ToInt32(enumValue).ToString();
                dt.Rows.Add(dr);
            }
            dt.AcceptChanges();
            tree.Nodes.Clear();
            tree.DataSource = dt;
        }

        public static void BindComboboxByEnum(EsolComboBox comboBox, Type enumType, Type valueMemberType, bool nullRow)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ValueMember", valueMemberType);
            dt.Columns.Add("DisplayMember", typeof(string));
            if (nullRow)
            {
                DataRow row = dt.NewRow();
                row["DisplayMember"] = "";
                row["ValueMember"] = DBNull.Value;
                dt.Rows.Add(row);
            }

            Array array = Enum.GetValues(enumType);
            foreach (Enum enumValue in array)
            {
                DataRow dr = dt.NewRow();
                dr["DisplayMember"] = enumValue.ToString();
                dr["ValueMember"] = Convert.ToInt32(enumValue).ToString();
                dt.Rows.Add(dr);
            }
            dt.AcceptChanges();
            comboBox.DisplayMember = "DisplayMember";
            comboBox.ValueMember = "ValueMember";
            comboBox.DataSource = dt;
        }

        public static void BindGridComboboxByEnum(RepositoryItemGridLookUpEdit comboBox, Type enumType, Type valueMemberType, bool nullRow)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ValueMember", valueMemberType);
            dt.Columns.Add("DisplayMember", typeof(string));
            if (nullRow)
            {
                DataRow row = dt.NewRow();
                row["DisplayMember"] = "";
                row["ValueMember"] = DBNull.Value;
                dt.Rows.Add(row);
            }

            Array array = Enum.GetValues(enumType);
            foreach (Enum enumValue in array)
            {
                DataRow dr = dt.NewRow();
                dr["DisplayMember"] = enumValue.ToString();
                dr["ValueMember"] = Convert.ToInt32(enumValue).ToString();
                dt.Rows.Add(dr);
            }
            dt.AcceptChanges();
            comboBox.DisplayMember = "DisplayMember";
            comboBox.ValueMember = "ValueMember";
            comboBox.DataSource = dt;
        }

        public static void BindComboboxByCommonItem(EsolComboBox comboBox, string itemType, bool nullRow)
        {
            List<MstCommonItemEntity> list = MstCommonItemBs.GetMstCommonItemListByType(itemType);
            if (nullRow)
            {
                MstCommonItemEntity entity = new MstCommonItemEntity();
                list.Insert(0, entity);
            }
            comboBox.DisplayMember = "ItemName";
            comboBox.ValueMember = "ItemCode";
            comboBox.DataSource = list;
        }

        public static void BindGridComboboxByCommonItem(RepositoryItemGridLookUpEdit comboBox, string itemType, bool nullRow)
        {
            List<MstCommonItemEntity> list = MstCommonItemBs.GetMstCommonItemListByType(itemType);
            if (nullRow)
            {
                MstCommonItemEntity entity = new MstCommonItemEntity();
                list.Insert(0, entity);
            }
            comboBox.DisplayMember = "ItemName";
            comboBox.ValueMember = "ItemCode";
            comboBox.DataSource = list;
        }

        public static void BindGridComboboxByCommonItemWithCode(RepositoryItemGridLookUpEdit comboBox, string itemType, bool nullRow)
        {
            List<MstCommonItemEntity> list = MstCommonItemBs.GetMstCommonItemListByType(itemType);
            if (nullRow)
            {
                MstCommonItemEntity entity = new MstCommonItemEntity();
                list.Insert(0, entity);
            }
            foreach (MstCommonItemEntity entity in list)
            {
                if (string.IsNullOrEmpty(entity.ItemCode) == false)
                {
                    entity.ItemName = entity.ItemCode.Replace(itemType, "") + ") " + entity.ItemName;
                }
            }
            comboBox.DataSource = list;
            comboBox.DisplayMember = "ItemName";
            comboBox.ValueMember = "ItemCode";
        }
        
        public static void BindComboboxByLocation(EsolComboBox comboBox, string warehouseCode, bool nullRow)
        {
            List<MstLocationEntity> list = MstLocationBs.GetAllLocation(warehouseCode);
            if (nullRow)
            {
                MstLocationEntity entity = new MstLocationEntity();
                list.Insert(0, entity);
            }
            comboBox.DisplayMember = "LocationName";
            comboBox.ValueMember = "LocationId";
            comboBox.DataSource = list;
        }

        public static void BindGridComboboxByLocation(DataGridViewComboBoxColumn comboBox, string warehouseCode, bool nullRow)
        {
            List<MstLocationEntity> list = MstLocationBs.GetAllLocation(warehouseCode);
            if (nullRow)
            {
                MstLocationEntity entity = new MstLocationEntity();
                list.Insert(0, entity);
            }
            comboBox.DisplayMember = "LocationName";
            comboBox.ValueMember = "LocationId";
            comboBox.DataSource = list;
        }
        public static void BindGridComboboxByLocation(RepositoryItemGridLookUpEdit comboBox, string warehouseCode, bool nullRow)
        {
            List<MstLocationEntity> list = MstLocationBs.GetAllLocation(warehouseCode);
            if (nullRow)
            {
                MstLocationEntity entity = new MstLocationEntity();
                list.Insert(0, entity);
            }
            comboBox.DisplayMember = "LocationName";
            comboBox.ValueMember = "LocationId";
            comboBox.DataSource = list;
        }
        
        public static void BindComboboxByArea(EsolComboBox comboBox, string ParentArerName, string AreaType, bool nullRow)
        {
            DataTable dt = new DataTable();
            string sCondotion = "";
            if (string.IsNullOrEmpty(ParentArerName))
                sCondotion += " AND A.AREA_TYPE ='" + AreaType + "' ";
            else sCondotion += " AND A.AREA_TYPE ='" + AreaType + "' AND PA.AREA_NAME='" + ParentArerName + "' ";

            dt = MstAreaBs.GetAreaByCondition(sCondotion, "", "");
            if (nullRow)
            {
                DataRow row = dt.NewRow();
                dt.Rows.InsertAt(row, 0);
            }
            dt.AcceptChanges();
            comboBox.ValueMember = "AREA_NAME";
            comboBox.DisplayMember = "AREA_NAME";
            comboBox.DataSource = dt;
        }

        public static void SetTextBoxPersonName(DevTextEdit txt, string personID)
        {
            if (string.IsNullOrEmpty(personID))
            {
                txt.Text = "";
                return;
            }
            MstPersonEntity person = MstPersonBs.GetMstPersonByID(personID);
            if (person != null)
            {
                txt.Text = person.NameCn;
                txt.Tag = person;
                return;
            }
            else
            {
                SecUserEntity user = SecUserBs.GetUserByID(personID);
                if (user != null)
                {
                    person = MstPersonBs.GetMstPersonByID(user.PersonId);
                    if (person != null)
                    {
                        txt.Text = person.NameCn;
                        txt.Tag = person;
                        return;
                    }
                }
                txt.Text = "";
            }
        }

        public static void SetTextBoxDate(DevTextEdit txt, DateTime date, string format)
        {
            if (date.ToString("yyyy-MM-dd") == "0001-01-01" || date.ToString("yyyy-MM-dd") == "1900-01-01")
            {
                txt.Text = "";
            }
            else
            {
                txt.Text = date.ToString(format);
            }
        }

        public static void BindContactCombobox(EsolComboBox comboBox, string customerId, bool nullRow)
        {
            List<MstCustomerContactEntity> list = MstCustomerContactBs.GetByCustomerId(customerId);
            if (list == null)
            {
                list = new List<MstCustomerContactEntity>();
            }
            if (nullRow)
            {
                MstCustomerContactEntity entity = new MstCustomerContactEntity();
                list.Insert(0, entity);
            }
            comboBox.DataSource = list;
            comboBox.DisplayMember = "ContactName";
            comboBox.ValueMember = "ContactId";
        }

        public static void BindSupplierContactCombobox(EsolComboBox comboBox, string supplierID, bool nullRow)
        {
            List<MstSupplierContactEntity> list = MstSupplierContactBs.GetDtSupplierContactsBySupplierID(supplierID);
            if (list == null)
            {
                list = new List<MstSupplierContactEntity>();
            }
            if (nullRow)
            {
                MstSupplierContactEntity entity = new MstSupplierContactEntity();
                list.Insert(0, entity);
            }
            comboBox.DataSource = list;
            comboBox.DisplayMember = "ContactName";
            comboBox.ValueMember = "ContactId";
        }

        public static void SetTextBoxDepartmentName(DevTextEdit txt, string DepartmentID)
        {
            if (string.IsNullOrEmpty(DepartmentID))
            {
                txt.Text = "";
                txt.Tag = null;
                return;
            }
            MstDepartmentEntity mDepartment = MstDepartmentBs.GetMstDepartmentByID(DepartmentID);
            if (mDepartment != null)
            {
                txt.Text = mDepartment.DepartmentName;
                txt.Tag = mDepartment;
            }
            else
            {
                txt.Text = "";
                txt.Tag = null;
            }
        }

        public static void BindContactGridCombobox(DataGridViewComboBoxColumn comboBox, string customerId, bool nullRow)
        {
            List<MstCustomerContactEntity> list = MstCustomerContactBs.GetByCustomerId(customerId);
            if (list == null)
            {
                list = new List<MstCustomerContactEntity>();
            }
            if (nullRow)
            {
                MstCustomerContactEntity entity = new MstCustomerContactEntity();
                list.Insert(0, entity);
            }
            comboBox.DataSource = list;
            comboBox.DisplayMember = "ContactName";
            comboBox.ValueMember = "ContactId";
        }
        public static void BindContactGridCombobox(RepositoryItemGridLookUpEdit comboBox, string customerId, bool nullRow)
        {
            List<MstCustomerContactEntity> list = MstCustomerContactBs.GetByCustomerId(customerId);
            if (list == null)
            {
                list = new List<MstCustomerContactEntity>();
            }
            if (nullRow)
            {
                MstCustomerContactEntity entity = new MstCustomerContactEntity();
                list.Insert(0, entity);
            }
            comboBox.DataSource = list;
            comboBox.DisplayMember = "ContactName";
            comboBox.ValueMember = "ContactId";
        }

        public static void BindSupplierContactGridComobox(DataGridViewComboBoxColumn comboBox, string supplierId, bool nullRow)
        {
            List<MstSupplierContactEntity> list = MstSupplierContactBs.GetDtSupplierContactsBySupplierID(supplierId);
            if (list == null)
            {
                list = new List<MstSupplierContactEntity>();
            }
            if (nullRow)
            {
                MstSupplierContactEntity entity = new MstSupplierContactEntity();
                list.Insert(0, entity);
            }
            comboBox.DataSource = list;
            comboBox.DisplayMember = "ContactName";
            comboBox.ValueMember = "ContactId";

        }

        public static MstCustomerContactEntity GetMainCustomerContact(string customerId)
        {
            MstCustomerContactEntity entity = MstCustomerContactBs.GetByCustomer(customerId, "CLEVEL01");
            if (entity == null)
            {
                entity = MstCustomerContactBs.GetByCustomer(customerId, "");
            }
            return entity;
        }

        public static MstSupplierContactEntity GetMainSupplierContact(string supplierId)
        {
            MstSupplierContactEntity entity = MstSupplierContactBs.GetBySupplier(supplierId, "CLEVEL01");
            if (entity == null)
            {
                entity = MstSupplierContactBs.GetBySupplier(supplierId, "");
            }
            return entity;
        }
        
        /// <summary>
        /// 判断用户是否可以查询其它用户的资料
        /// </summary>
        public static bool CheckPersonRight(RoleCategory role)
        {
            if (CommonParameter.CurrentUser == null)
            {
                return false;
            }
            if (CommonParameter.CurrentUser.PersonId == "1")
            {
                return true;
            }
            else
            {
                //1=总经理；2=财务；3=人事；4=销售
                if (CommonParameter.CurrentUser.UserRoleCategory.Contains("1") || CommonParameter.CurrentUser.UserRoleCategory.Contains(role.GetHashCode().ToString()))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 判断用户是否可以查询其它用户的资料,根据审核权限判断
        /// </summary>
        public static bool CheckPersonRight(string sFormName, string sObjectCode)
        {
            if (CommonParameter.CurrentUser == null)
            {
                return false;
            }
            if (CommonParameter.CurrentUser.PersonId == "1")
            {
                return true;
            }
            else
            {
                if (MstMessageBs.CheckPersonRightByFormAndObject(CommonParameter.CurrentUser.PersonId, sFormName, sObjectCode))
                {
                    return true;
                }
            }
            return false;
        }

        public static string GetApplicationVersion()
        {
            MemoryStream memStream;
            using (FileStream stream = new FileStream(Application.StartupPath + "\\ESOL.WinUI.exe", FileMode.Open))
            {
                using (memStream = new MemoryStream())
                {
                    int res;
                    byte[] b = new byte[4096];
                    while ((res = stream.Read(b, 0, b.Length)) > 0)
                    {
                        memStream.Write(b, 0, b.Length);
                    }
                }
            }
            Assembly assDllLocal = Assembly.Load(memStream.ToArray());
            string latestVersion = assDllLocal.GetName().Version.ToString();
            memStream.Dispose();
            return latestVersion;
        }

        public static void BindComboboxByCommonItemWithCode(EsolComboBox comboBox, string itemType, bool nullRow)
        {
            List<MstCommonItemEntity> list = MstCommonItemBs.GetMstCommonItemListByType(itemType);
            if (nullRow)
            {
                MstCommonItemEntity entity = new MstCommonItemEntity();
                list.Insert(0, entity);
            }
            foreach (MstCommonItemEntity entity in list)
            {
                if (string.IsNullOrEmpty(entity.ItemCode) == false)
                {
                    entity.ItemName = entity.ItemCode.Replace(itemType, "") + ") " + entity.ItemName;
                }
            }
            comboBox.DataSource = list;
            comboBox.DisplayMember = "ItemName";
            comboBox.ValueMember = "ItemCode";
        }
        public static void BindGridComboboxByCommonItemWithCode(DataGridViewComboBoxColumn comboBox, string itemType, bool nullRow)
        {
            List<MstCommonItemEntity> list = MstCommonItemBs.GetMstCommonItemListByType(itemType);
            if (nullRow)
            {
                MstCommonItemEntity entity = new MstCommonItemEntity();
                list.Insert(0, entity);
            }
            foreach (MstCommonItemEntity entity in list)
            {
                if (string.IsNullOrEmpty(entity.ItemCode) == false)
                {
                    entity.ItemName = entity.ItemCode.Replace(itemType, "") + ") " + entity.ItemName;
                }
            }
            comboBox.DataSource = list;
            comboBox.DisplayMember = "ItemName";
            comboBox.ValueMember = "ItemCode";
        }

        public static void SetControlsEnable(Control.ControlCollection coltrols, bool enable)
        {
            if (coltrols == null)
            {
                return;
            }
            foreach (Control c in coltrols)
            {
                if (c is DevButton || c is DevLabel || c is ProgressBar || c is DevTreeList || c is DevDataGridView||
                    c is DevGroupControl || c is DevTabControl || c is DevPanel||c is DevButtonEdit)
                {
                    continue;
                }
                else if (c is DevTextEdit)
                {
                    ((DevTextEdit)c).Properties.ReadOnly = !enable;
                }
                else
                {
                    c.Enabled = enable;
                }
                SetControlsEnable(c.Controls, enable);
            }
        }

        /// <summary>
        /// 判断DevGridView所绑定的DataTable的必填项是否存在空值
        /// </summary>
        /// <param name="dgv"></param>
        /// <returns></returns>
        public static bool CheckDataGrid(DevDataGridView dgv)
        {
            GridView gv = (GridView)dgv.Views[0];
            for (int i = 0; i < gv.Columns.Count; i++)
            {
                if (gv.Columns[i].AppearanceHeader.ForeColor == Color.Red)
                {
                    DataTable dt = dgv.DataSource as DataTable;
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        string sFieldName=gv.Columns[i].FieldName;

                        if (dt.Rows[j][sFieldName] == null||string.IsNullOrEmpty(dt.Rows[j][sFieldName].ToString()) == true)
                        {
                            MessageBox.Show(gv.Columns[i].Caption + "不能为空（第" + (j + 1).ToString() + "行）", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;   
                        }
                    }
                }
            }
            return true;
        }
        public static bool CheckDataGrid(DevDataGridView dgv,out string msg)
        {
            msg = "";
            GridView gv = (GridView)dgv.Views[0];
            for (int i = 0; i < gv.Columns.Count; i++)
            {
                if (gv.Columns[i].AppearanceHeader.ForeColor == Color.Red)
                {
                    DataTable dt = dgv.DataSource as DataTable;
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        string sFieldName = gv.Columns[i].FieldName;
                        if (dt.Rows[j][sFieldName] == null||string.IsNullOrEmpty(dt.Rows[j][sFieldName].ToString()) == true)
                        {
                            //MessageBox.Show(gv.Columns[i].Caption + "不能为空（第" + (j + 1).ToString() + "行）", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            msg = gv.Columns[i].Caption + "不能为空（第" + (j + 1).ToString() + "行）";
                            return false;
                        }
                        
                    }
                }
            }
            return true;
        }
    }

}
